<?php
namespace Suning;

use QL\QueryList;

class SuningParser
{

    public function parseOrderList($str)
    {
        $result = [];
        if($ret = $this->jsonPreProcess($str) && isset($ret['orderList'])){
            $time = time() * 1000;
            $new_task = $this->getTaskType(__FUNCTION__);
            foreach ($ret['orderList'] as $orderInfo) {
                $tmp['order_id'] = $orderInfo['orderId'];
                $tmp['price'] = $orderInfo['orderAmt'];
                $tmp['buy_at'] = $orderInfo['submitTime'];
                $vendorInfo = current($orderInfo['vendorList']);
                if($vendorInfo['orderStatus'] === '已完成'){
                    continue;
                }
                $tmp['status'] = (int)($vendorInfo['orderStatus'] === '已完成');
                $tmp['seller'] = $vendorInfo['vendorName'];

                $productInfo = current($vendorInfo['itemList']);
                $tmp['title'] = preg_replace('/[\s\p{Z}]/iu','', $productInfo['productName']);

                $tmp['img_url'] = $this->getImgUrl($vendorInfo['vendorCode'], $productInfo['partNumber']);
                $tmp['url'] = $this->getDetailUrl($tmp['order_id'], $vendorInfo['vendorCode'], $time+1000);
                $tmp['new_task'] = $new_task;
                $result[] = $tmp;
            }
        }
        return $result;
    }

    public function parseOrderDetail($str)
    {
        $result = [];
        if($data = $this->jsonPreProcess($str)){
            if($data['cShopName'] && count($data['cShopOrderList'])){
                $userInfo = current($data['cShopOrderList']);
            }elseif(count($data['ordersDisplay'])){
                $userInfo = current($data['ordersDisplay']);
            }
            if(isset($userInfo) && $userInfo){
                $tmp = [];
                $tmp['receive_address'] = $userInfo['address'];
                $tmp['receive_mobile'] = $userInfo['itemMobilePhone'];
                $tmp['receive_user'] = $userInfo['itemPlacerName'];
                $tmp['order_id'] = $data['orderId'];
                $tmp['url'] =
                $tmp['new_task'] = $this->getTaskType(__FUNCTION__);
                $result = $tmp;
            }
        }
        return $result;
    }

    /**
     * parseExpressInfos
     *
     * @return array
     */
    public function parseExpressInfos($str)
    {
        $items_container = '#changeContent1';
        $rules = [
            'express_number' => ['div.new-order-track > span:eq(0)', 'text', '', function($str){
                return preg_replace('/订单编号(?:：|:)\s*/i', '', $str);
            }],
            'order_status' =>['div.new-order-track > span:eq(1)','text', '', function($str){
                return preg_replace('/状态(?:：|:)\s*/i', '', $str) === '完成' ? 1 : 0;
            }],
            'logistics' => ['ul.new-of-storey > li > span', 'text','', function($data){
                return preg_replace('/(\d{4}-\d{2}-\d{2}\s(?:\d{2}:){2}\d{2})/','##$1###', $data);
            }],
        ];
        if($data = QueryList::query($str, $rules, $items_container)->getData()){
            $data = $data[0];
            $data['arrive_at'] = preg_match('/订单预计.*送达/', $data['logistics'], $match) ? $match[0] : '';
            $data['express_number'] = preg_match('/运单号为([\dA-Za-z]*)/', $data['logistics'], $match) ? $match[1] : $data['express_number'];
            $data['express_infos'] = array_map(function($str){
                return implode('  ', array_reverse(explode('##', $str)));
            }, explode('###', $data['logistics']));
            // preg_split('/(?:[\s\t]|&nbsp;)+/', htmlentities($data['express_infos'][0]));
            if($last_info = preg_split('/(?:\s|\t|\p{Z})+/u', $data['express_infos'][0])){
                $data['brand_name'] = end($last_info) ?: '';
            }
            $data['express_infos'] = trim(implode('|||', array_reverse($data['express_infos'])), '|');

        }
        return $data;
    }

    /**
     * @param string $vendorId
     * @param string $productId
     * @return string
     */
    private function getImgUrl($vendorId, $productId)
    {
        return $this->getImgHost().sprintf(self::SN_IMG_URL_TPL, $vendorId, $productId);
    }

    /**
     * @return string
     */
    private function getImgHost()
    {
        return $this->imgHost ?: $this->imgHost = sprintf(self::SN_IMG_HOST_TPL, mt_rand(1, 3));
    }

    /**
     * @param string $orderId
     * @param string $supplierCode
     * @param string $timeNow
     * @return string
     */
    private function getDetailUrl($orderId, $supplierCode, $timeNow)
    {
        return sprintf(self::ORDER_DETAIL_URL_TPL, $this->buildOrderDetailParams($orderId, $supplierCode), $timeNow);
    }

    /**
     * 初步测试,官方的不需要supplierCode
     * @param string $orderId
     * @param string $supplierCode
     * @return string
     */
    private function buildOrderDetailParams($orderId, $supplierCode)
    {
        $str = $orderId;
        if($supplierCode !== self::SN_OFFICIAL_ID){
            $str .= '&supplierCode='.$supplierCode;
        }
        return $str;
    }

    /**
     * jsonPreProcess
     *
     * @param  string $str
     * @param  string $callback
     * @return array|null
     */
    private function jsonPreProcess($str)
    {
        $str = trim(strip_tags($str));
        if (preg_match('#(?:\{|\[).*(?:\]|\})#isS', $str, $match)) {
            $str = stripslashes($match[0]);
        }
        $arr = json_decode($str, true);
        return json_last_error() === JSON_ERROR_NONE ? $arr : null;
    }
}
